<script setup>
import { MdPreview } from 'md-editor-v3';
import { useRoute } from "vue-router";
import requester from "~/utils/request";
const router = useRoute()
import { userStore } from "~/composables/useUserStore";
import NewKefu from '~/components/newKefu.vue';
import { InfoFilled, Loading, ArrowLeftBold } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus'
const store = userStore()
//商品编号
const productId = router.params.id
// 文档列表
const options = reactive({
  width: '100%', //播放器高度
  // height: '250px', //播放器高度
  type:"video/mp4",
  color: "#409eff", //主题色
  title: '', //视频名称
  muted: false, //静音
  webFullScreen: false,
  speedRate: ["0.75", "1.0", "1.25", "1.5", "2.0"], //播放倍速
  // autoPlay: true, //自动播放
  loop: false, //循环播放
  mirror: false, //镜像画面
  ligthOff: false,  //关灯模式
  volume: 0.35, //默认音量大小
  control: true, //是否显示控制
  controlBtns:['audioTrack', 'quality', 'speedRate', 'volume', 'setting', 'pip', 'pageFullScreen', 'fullScreen'] //显示所有按钮,
})

const state = reactive({
  currentUrl:"",
  isDialogVisible:false,
  isMove:false,
  videoHeight:'100%',
  viewDialogVisible: false,
  previewSrc: "",
  scrollElement: "",
  showBg: true,
  width: 1600,
  info: {
    videoFiles: [{
      fileUrl: ''
    }],
    bzImps: [{
      fileUrl: ''
    }],
  },
  accreditCodeTemp:'',
  accreditCode: '',
  zhekouPrice: '',
  orderCode: '',
  payUrl: '',
  isUse: false,
  showOrder: false,
  // 当前文档选择
  currentDocIndex: null,
  // 订单价格列表
  orderArr: [],
  // 当前订单价格选择
  currentOrderIndex: 0,
  // 是否打开推荐码
  isUseCode: false,
})
//初始化
function init() {
  // wx.config({
  //   debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
  //   appId: 'wx4754a2bb841ba595', // 必填，公众号的唯一标识
  //   timestamp: new Date().getTime(), // 必填，生成签名的时间戳
  //   nonceStr: 'Wm3WZYTPz0wzccnW', // 必填，生成签名的随机串
  //   signature: '11',// 必填，签名
  //   jsApiList: [] // 必填，需要使用的JS接口列表
  // });


  //获取数据
  getProduct()
}
let orderTimer

// 获取支付二维码
function payOption() {
  // 判断是否为移动端
  const isMobile = /Mobi|Android/i.test(navigator.userAgent);
  if (isMobile){
    state.isDialogVisible = true
    const currentUrl = window.location.href;  // 获取当前页面的完整URL
    state.currentUrl = window.location.href;  // 获取当前页面的完整URL
    // 使用Clipboard API将URL复制到剪贴板
    navigator.clipboard.writeText(currentUrl).then(() => {
      ElMessage.success('移动端不支持购买！已将链接复制到您手机中，请切换到电脑端！')
      return; // 在这里返回，结束函数
    }).catch(err => {
      console.error('Failed to copy: ', err);
      ElMessage.error('复制链接失败，请重试。'); // 提示用户复制失败
    });
    return; // 确保在移动端操作后不再继续执行下面的代码
  }

  if (!store.isLogin) {
    store.visiable = true
    return;
  }
  clearTimeout(orderTimer)
  state.showOrder = true;
  requester.post('/api/order/payOption', {
    "accreditCode": state.accreditCode,
    "buyType": state.orderArr[state.currentOrderIndex].buyType,
    "products": productId,
    "userCode": store.token.userCode
  }).then((res) => {
    if (res.code == 200) {
      state.payUrl = res.data.payUrl
      state.orderCode = res.data.orderCode
      state.accreditCode = ''
      state.isUse = true
      getOrder()
    } else {
      state.accreditCode = ''
      ElMessage.error(res.msg)
      state.showOrder = false
    }
  })
}
//获取订单
function getOrder() {
  if (!state.isUse) return
  requester.post('/api/order/getOrder', {
    orderCode: state.orderCode,
    userCode: store.token.userCode
  }).then((res) => {
    if (res.data.status == 0) {
      orderTimer = setTimeout(() => {
        getOrder()
      }, 3000)
    }
    if (res.data.status == -1) {
      clearTimeout(orderTimer)
      payOption()
    }
    if (res.data.status == 2) {
      clearTimeout(orderTimer)
      ElMessage.success('支付成功！')
      state.showOrder = false
      //跳转个人
      navigateTo('/my?tabIndex=2')
    }
  })
}

//获取商品信息
function getProduct() {
  const param = {
    productId: productId,
    // userCode: "",
  }
  if (store.isLogin) {
    param.userCode = store.token.userCode
  }
  requester.post('/api/product/getProduct', param).then((res) => {
    if (res.code == 200) {
      state.info = res.data

      //增加SEO
      useHead({
        title: '资源详情',
        titleTemplate: state.info.productName + ' - 项目详情',
        meta: [
          { hid: 'keywords', name: 'keywords', content: '资源' }
        ],
        link: [
          {rel: 'stylesheet', href: 'https://res.wx.qq.com/open/libs/weui/2.3.0/weui.min.css'}
        ],
        script: [
          {
            src: 'https://res.wx.qq.com/open/libs/weuijs/1.2.1/weui.min.js',
            type: 'text/javascript',
          },
        ]
      })

      if (state.info.bzImps[0] && state.info.bzImps[0].fileUrl && state.info.bzImps[0].fileUrl.includes('<iframe')) {
        if (document.documentElement.clientWidth < 768) {
          state.info.bzImps[0].fileUrl = state.info.bzImps[0].fileUrl.replace('<iframe', '<iframe style="width:100%;height:25vh"')
        } else {
          state.info.bzImps[0].fileUrl = state.info.bzImps[0].fileUrl.replace('<iframe', '<iframe style="width:100%;height:53vh"')
        }
      }
      if (state.info.productTag) state.info.productTag = state.info.productTag.split(',')
      // state.info.documentList = [
      //   {
      //     fileName: "测试文档",
      //     url: "https://xunying-xcp.oss-cn-shanghai.aliyuncs.com/%E5%9F%BA%E4%BA%8ESpark%E7%9A%84%E9%AA%91%E8%A1%8C%E8%A3%85%E5%A4%87%E6%8E%A8%E8%8D%90%E7%B3%BB%E7%BB%9F%E4%B8%8E%E5%AE%9E%E7%8E%B0-%E5%BC%80%E9%A2%98%E6%8A%A5%E5%91%8A08121125.doc"
      //   },
      //   {
      //     fileName: "测试文档2",
      //     url: "https://xunying-xcp.oss-cn-shanghai.aliyuncs.com/%E5%9F%BA%E4%BA%8ESpark%E7%9A%84%E9%AA%91%E8%A1%8C%E8%A3%85%E5%A4%87%E6%8E%A8%E8%8D%90%E7%B3%BB%E7%BB%9F%E4%B8%8E%E5%AE%9E%E7%8E%B0-%E5%BC%80%E9%A2%98%E6%8A%A5%E5%91%8A08121125.doc"
      //   },
      // ]
      state.orderArr = [
        {
          desc:"基础版",
          name: "源码下载",
          price: state.info.priceCurrentPrice,
          buyType: "1"
        },
        {
          desc:"进阶版",
          name: "源码下载+远程部署",
          price: state.info.priceDeploy,
          buyType: "2"
        },
        {
          desc:"高阶版",
          name: "源码下载+远程部署+技术指导",
          price: state.info.priceGuide,
          buyType: "3"
        },
      ]


    }
  })
}

//喜欢
function like() {
  //判断是否登录
  if (!store.isLogin) {
    store.visiable = true
    return;
  }
  requester.post('api/product/updPraise', {
    productId: productId,
    userCode: store.token.userCode
  }).then(() => {
    getProduct()
  })
}

// 选择文档
function selectDoc(item, index) {
  //打开预览框
  state.viewDialogVisible = true
  requester.get(`/api/product/view?url=${item.url}`).then(res =>{
    state.previewSrc = res.msg
  })


  state.currentDocIndex = index

}



// 检测推荐码
function checkAccreditCode() {
  state.accreditCode = state.accreditCodeTemp
  requester.post('/api/user/checkAccreditCode', {
    accreditCode: state.accreditCode,
    // userCode: store.token.userCode
  }).then((res) => {
    if (res.code == 200) {
      clearTimeout(orderTimer)
      ElMessage.success('使用成功');
      state.zhekouPrice = state.info.priceAccreditRate
      state.orderArr.forEach(element => {
        element.zhekouPrice = (element.price*state.zhekouPrice).toFixed(2)
      });
      console.log(state)
      payOption()
    } else {
      state.accreditCode = ""
      ElMessage.error(res.msg);
    }
  })
}
// 退回
function cancelCode(){
  state.isUseCode = false;
  state.zhekouPrice = '';
  state.accreditCodeTemp = '';
  state.accreditCode = ''
}

init()



onMounted(()=>{
  const userAgent = navigator.userAgent || navigator.vendor || window.opera;
  if (/android|iPad|iPhone|iPod/.test(userAgent) && !window.MSStream){
    state.videoHeight = "200px"
    state.isMove = true;
  }else {
    state.videoHeight = "100%"
    state.isMove = false;
  }
})

</script>

<template>
  <!-- 标头 -->
  <myheader />
  <div class="main">
    <div class="bgCon">
      <div class="bgConChild bgConChild1"></div>
      <div class="bgConChild bgConChild2"></div>
      <div class="bgConChild bgConChild3"></div>
    </div>
    <div class="conWarp">
      <div class="titleCon">
        <div class="back" @click="navigateTo('/')">
          <img src="@/assets/details/back.png" alt="">
        </div>
        <h1 class="title">{{ state.info.productName }}</h1>
      </div>
      <el-dialog class="orderDialog" title="确认订单" v-model="state.showOrder" :z-index="2000">
        <div class="orderBg">
          <div class="orderItems">
            <div :class="[state.currentOrderIndex == index ? 'active' : '', 'orderItem']"
              v-for="(item, index) in state.orderArr" @click="state.currentOrderIndex = index;payOption()">
              <div class="orderTag">
                {{ item.desc }}
              </div>
              <div class="title" >
                {{ item.name }}
              </div>
              <div class="flex price">
                <span style="font-size: 16px;">￥</span>
                <span>{{ state.zhekouPrice ? item.zhekouPrice : item.price }}</span>
              </div>
              <div class="button">
                购买后立即下载资料
              </div>
            </div>
          </div>

          <div class="flex orderBottom">
            <div class="payCode">
              <el-image :src="state.payUrl">
                <template #error>
                  <div class="image-slot">
                    <el-icon class="is-loading">
                      <Loading />
                    </el-icon>
                    <span>Loading</span>
                  </div>
                </template>
              </el-image>
            </div>

            <div class="payItem">
              <div class="flex needPrice">
                <p>应付金额：</p>
                <div class="flex price">
                  <span style="font-size: 16px;">￥</span>
                  <span>{{
                    state.zhekouPrice ? state.orderArr[state.currentOrderIndex].zhekouPrice :
                      state.orderArr[state.currentOrderIndex].price
                  }}</span>
                </div>
              </div>
              <div class="flex wechatPay">
                <img src="@/assets/details/wechat.png" alt="">
                <p>支持微信扫码支付</p>
              </div>
            </div>

            <div class="inputItem">
              <div class="inputText fs18" @click="state.isUseCode = true">推荐码购买</div>
              <div class="flex inputBox" v-if="state.isUseCode">
                <el-input placeholder="请输入推荐码" class="payInput" v-model="state.accreditCodeTemp"
                  @keyup.enter="checkAccreditCode()"></el-input>
                <el-button type="primary" size="small" @click="checkAccreditCode()">使用</el-button>
                <span class="cancelCode" @click="cancelCode()">退回</span>
              </div>
            </div>

            <div class="flex introItem">
              <div class="intro-left">
                <span>
                  <p style="margin-right: 5px;">说明</p>
                  <el-icon :size="15">
                    <InfoFilled />
                  </el-icon>
                </span>
              </div>
              <div class="intro-right">如何您购买的是部署和指导订单，请下单之后联系客户预约时间进行项目部署！</div>
            </div>
          </div>
        </div>
      </el-dialog>

      <div class="conWarp-box">
        <div class="conWarp-left">
          <div class="videoCon">
            <div class="mobileBox">
              <div class="mobileBack" @click="navigateTo('/')">
                <el-icon size="26" color="#ffffff">
                  <ArrowLeftBold />
                </el-icon>
              </div>
            </div>

            <vue3-video-play
              v-bind="options"
              v-if="state.info.videoFiles[0] && state.info.videoFiles[0].fileUrl && state.info.videoFiles[0].fileUrl.includes('video/') && !state.isMove"
              :src="state.info.videoFiles[0].fileUrl" class="w_100">
            </vue3-video-play>

            <iframe
                style="height: 200px"
                v-else-if="state.info.videoFiles[0] && state.info.videoFiles[0].fileUrl && state.info.videoFiles[0].fileUrl.includes('video/')  && state.isMove"
                :src="state.info.videoFiles[0].fileUrl" class="w_100">
            </iframe>
            <div style="width:100%;height:100%;" class="iframeVideo"
              v-else-if="state.info.bzImps[0] && state.info.bzImps[0].fileUrl && state.info.bzImps[0].fileUrl.includes('<iframe')"
              v-html="state.info.bzImps[0].fileUrl"></div>
            <div v-else class="center" style="margin-top:20px;flex-wrap:wrap;">
              <img style="margin: 0 auto ;width: 100%;"
                src="https://pay.huijinwei.com/oilAdmin/assets/not_data.7ccb6760.png" />
              <div style="color:#999;width:100%;text-align:center;">视屏资源不见了~</div>
            </div>
          </div>

          <div class="likeCon">
            <div class="mobileBox">
              <div class="title">
                {{ state.info.productName }}
              </div>
              <div>
                <div class="tags">
                  <div class="tag" v-for="(item, index) in state.info.productTag" :key="index">{{ item }}</div>
                </div>
              </div>
              <div class="productIntro">
                <div>作品简介：{{ state.info.productIntro }}</div>
              </div>
            </div>

            <div class="likeItems">
              <div class="likeItem" @click="like()">
                <img v-if="state.info.isPraise == 0" src="@/assets/details/like.png" alt="">
                <img v-if="state.info.isPraise == 1" src="@/assets/details/like1.png" alt="">
                <div v-if="store.isLogin">
                  {{ state.info.praiseNum }}
                </div>
              </div>
              <div class="likeItem">
                <img src="@/assets/details/share.png" alt="" @click="copy()">
              </div>
            </div>

            <div class="mobileBox">
              <div class="likeBottom">
                <img class="mobileBg" src="@/assets/details/mobileBg.png" alt="">
                <div>
                  <span>价格：</span>
                  <span class="color-red">￥</span>
                  <span class="color-red">{{ state.info.priceCurrentPrice }}</span>
                </div>
                <div>
                  <div class="buyBox">
                    <el-button class="buyBtn" type="primary" @click.native="payOption()">立即付款</el-button>
                  </div>
                </div>
              </div>
            </div>


          </div>

          <div class="detailCon">
            <h1 class="title">
              作品介绍：
            </h1>
            <div>
              <MdPreview editorId="preview-only" :modelValue="state.info.productDesc" />
            </div>
          </div>
        </div>

        <div class="conWarp-right">
          <div class="rightItem priceCon">
            <img src="@/assets/details/rightBg.png" alt="" class="rightBg">
            <div class="priceTitle">
              <div class="fb">
                <span class="fs18 color-black2">价格：</span><span class="color-red">￥</span><span
                  class="color-red fs30">{{state.info.priceCurrentPrice }}</span>
              </div>

              <div class="buyBox">
                <el-button class="buyBtn" type="primary" @click="payOption()">立即付款</el-button>
              </div>
            </div>
            <div>
              <div class="right-title">商品标签</div>
              <div class="tags">
                <div class="tag" v-for="(item, index) in state.info.productTag" :key="index">{{ item }}</div>
              </div>
            </div>
            <div>
              <div class="right-title">作品简介</div>
              <div class="intro">
                {{ state.info.productIntro }}
              </div>
            </div>
          </div>
          <div class="rightItem docCon mt24" v-if="state.info.documentList && state.info.documentList.length != 0">
            <el-collapse model-value="1" accordion>
              <el-collapse-item name="1">
                <template #title>
                  <div class="conTitle" style="margin-bottom: 0;">
                    <img src="@/assets/details/doc.png" alt="">
                    <h1 style="padding-bottom: 0;">
                      文档列表
                    </h1>
                  </div>
                </template>
                <div>
                  <ul>
                    <li :class="state.currentDocIndex == index ? 'active' : ''"
                      v-for="(item, index) in state.info.documentList" :key="index" @click="selectDoc(item, index)">
                      {{ item.fileName }}
                    </li>
                  </ul>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>

          <div class="rightItem advantageCon mt24">
            <div class="p13">
              <div class="conTitle">
                <img src="@/assets/details/buy.png" alt="">
                <h1>商品购买优势</h1>
              </div>
              <div class="fs18 color-black2">
                <span>可能全网唯一“真的官方验”的</span>
                <span style="display: block;text-align: center">项目服务网站</span>
              </div>

              <div class="icons">
                <div class="iconItem">
                  <img src="@/assets/details/buyIcon1.png" alt="">
                  <p>拒绝项目缺失</p>
                </div>
                <div class="iconItem">
                  <img src="@/assets/details/buyIcon2.png" alt="">
                  <p>拒绝无售后</p>
                </div>
              </div>
            </div>

            <div class="bottomBox">
              <p class="content">这里您看到的所有项目都由我司工程师为您核验过，如果发现有
                遗漏之处请立即联系客服，挽回您的损失!</p>
              <div class="imgBox">
                <img src="@/assets/details/buyIcon3.png" alt="">
              </div>
              <p class="tip">脱离平台交易有诈骗风险，请慎重。</p>
            </div>
          </div>

          <div class="rightItem timeCon mt24" v-if="state.info.version && state.info.version.length != 0">
            <div class="p13">
              <div class="conTitle">
                <img src="@/assets/details/time.png" alt="">
                <h1>
                  时间线
                </h1>
              </div>
              <div>
                <el-timeline style="max-width: 600px">
                  <el-timeline-item v-for="(activity, index) in state.info.version" :key="index"
                    :timestamp="activity.time">
                    <template #dot>
                      <div class="dotBox">
                        <div class="dot-out"></div>
                        <div class="dot-inner"></div>
                      </div>
                    </template>
                    {{ activity.name }}
                  </el-timeline-item>
                </el-timeline>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>
  <NewKefu :documentList="state.info.documentList" />
  <el-dialog v-model="state.viewDialogVisible" title="预览" width="65%">
    <iframe style="width: 100%;height: 75vh" :src="state.previewSrc" ></iframe>
  </el-dialog>
  <myFooter />
  <!-- 弹窗内容 -->
  <div class="js_dialog"
       role="dialog"
       aria-hidden="true"
       aria-modal="true"
       aria-labelledby="js_title3"
       id="androidDialog2"
       v-if="state.isDialogVisible">
    <div class="weui-mask"></div>
    <div class="weui-dialog weui-skin_android">
      <div class="weui-dialog__hd">
        <strong class="weui-dialog__title" id="js_title3" style="font-weight: 500;font-size: 15px">移动端不支持购买！已将链接复制到您手机中，请切换到电脑端！</strong></div>
      <div class="weui-dialog__bd">
        <span style="font-size: 12px">链接地址为：{{state.currentUrl}}</span>
      </div>
      <div class="weui-dialog__ft">
        <a  role="button" href="javascript:" class="weui-dialog__btn weui-dialog__btn_default" @click="state.isDialogVisible = false">确定</a>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
@import "./index.scss";
</style>
